//
//  Base_BlueTooth.m
//  BleGPS
//
//  Created by 盈诺森 on 2019/12/6.
//  Copyright © 2019 盈诺森. All rights reserved.
//

#import "Base_BlueTooth.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "BleGPS-Swift.h"
#import "Mld.pbobjc.h"

@interface Base_BlueTooth ()<CBCentralManagerDelegate, CBPeripheralDelegate,LoggerDelegate, DFUServiceDelegate, DFUProgressDelegate>


#define ST_CHARACTERISTIC_UUID_READ @"6E400003-B5A3-F393-E0A9-E50E24DCCA9E"
#define ST_CHARACTERISTIC_UUID_WRITE @"6E400002-B5A3-F393-E0A9-E50E24DCCA9E"
#define ST_SERVICE_UUID @"6E400001-B5A3-F393-E0A9-E50E24DCCA9E"


@property(nonatomic, strong)CBCentralManager *centralManager;
@property (strong , nonatomic) CBPeripheral *bluetoothTemp;
@property (nonatomic, strong)NSMutableArray *deviceArray;
@property (nonatomic, strong) CBCharacteristic *read;
@property (nonatomic, strong) CBCharacteristic *write;

@property (strong, nonatomic) DFUServiceController *dfuController;
@property (strong, nonatomic) DFUFirmware *selectedFirmware;
@property (strong, nonatomic) DFUServiceController *controller;

@end

@implementation Base_BlueTooth

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    }
    return self;
}

- (void)startScan{
    self.deviceArray = [NSMutableArray arrayWithCapacity:0];
    [self.centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:@"54D50001-2E4B-4E2F-B71A-9FB3013F8044"]]
                                               options:nil];
//    [_centralManager scanForPeripheralsWithServices:nil options:nil];
    [self performSelector:@selector(delayMethod) withObject:nil/*可传任意类型参数*/ afterDelay:1.5];
}
            
//开始查看服务，蓝牙开启
-(void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    switch (central.state) {
        case CBManagerStatePoweredOn:
        {
            NSLog(@"蓝牙已打开,请扫描外设");
        }
            break;
        case CBManagerStatePoweredOff:
            NSLog(@"蓝牙没有打开,请先打开蓝牙");
            break;
        default:
            break;
    }
}

//查找设备
- (void)centralManager:(CBCentralManager*)central didDiscoverPeripheral:(CBPeripheral*)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber*)RSSI{
    NSDictionary *dic = @{
        @"name":peripheral.name,
        @"identifier":peripheral.identifier,
        @"RSSI":RSSI
    };
//    NSLog(@"%@",peripheral);
    [self.deviceArray addObject:dic];
}

- (void)centerDevice:(NSString *)uuidString{
    NSUUID *uuid = [[NSUUID UUID] initWithUUIDString:uuidString];
    NSArray *knownPeripherals = [self.centralManager retrievePeripheralsWithIdentifiers:@[uuid]];
    self.bluetoothTemp = knownPeripherals[0];
    [self.centralManager connectPeripheral:self.bluetoothTemp options:nil];
}

//连接设备
-(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
    NSLog(@"连接成功已经连接到:%@", peripheral.description);
    self.bluetoothTemp = peripheral;
    self.bluetoothTemp.delegate = self;
    [peripheral discoverServices:nil];
    self.connectionSucce([NSString stringWithFormat:@"{\"content\":\"连接成功\",\"device\":\"%@\"}",peripheral.name]);
}

//只要扫描到服务就会调用
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(nullable NSError *)error
{
     if (!error) {
           for (CBService *service in peripheral.services) {
               NSLog(@"serviceUUID:%@", service.UUID.UUIDString);
               if ([service.UUID.UUIDString isEqualToString:ST_SERVICE_UUID]) {
                           //发现特定服务的特征值
                   [service.peripheral discoverCharacteristics:nil forService:service];
               }
           }
       }
}

//获取读和写的characteristics
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
    
    if (error)
      {
          NSLog(@"Discovered characteristics for %@ with error: %@", service.UUID, [error localizedDescription]);
          return;
      }
    
    
    for (CBCharacteristic *characteristic in service.characteristics) {
        if ([characteristic.UUID.UUIDString isEqualToString:ST_CHARACTERISTIC_UUID_READ]) {
            self.read = characteristic;
            [self.bluetoothTemp setNotifyValue:YES forCharacteristic:characteristic];
        }
    }
    
    for (CBCharacteristic *characteristic in service.characteristics) {
        if ([characteristic.UUID.UUIDString isEqualToString:ST_CHARACTERISTIC_UUID_WRITE]){
            self.write = characteristic;
        }
        [peripheral discoverDescriptorsForCharacteristic:characteristic];
    }
}
//传入参数
- (void)sendCommand:(NSData *)command{
    
    [self.bluetoothTemp writeValue:command forCharacteristic:self.write type:CBCharacteristicWriteWithResponse];
}

- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error{
    self.connectionSucce(@"{\"content\":\"连接失败\"}");
}

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error{
    NSLog(@"蓝牙设备断开连接");
}

//是否写入成功的代理
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    if (error) {
        NSLog(@"===写入错误：%@",error);
    }else{
        NSLog(@"===写入成功");
    }
}

- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
    if([characteristic.UUID.UUIDString isEqualToString:ST_CHARACTERISTIC_UUID_READ]){
        //获取订阅特征回复的数据
        self.deviceReturn(characteristic.value);
    }
}

//延时1.5秒后返回扫描的设备
- (void)delayMethod{
    [self.centralManager stopScan];
    self.DeviceNameBlock(self.deviceArray);
}


-(void)initDFUService:(NSURL *)firmWareFilePath{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"mld_dfu_test_v200_" ofType:@"zip"];
       NSURL *url = [NSURL URLWithString:path];
    DFUFirmware *selectedFirmware = [[DFUFirmware alloc] initWithUrlToZipFile:url];
    DFUServiceInitiator *initiator = [[DFUServiceInitiator alloc] initWithCentralManager:self.centralManager target:self.bluetoothTemp];
    initiator = [initiator withFirmware:selectedFirmware]; //recommend
    initiator.packetReceiptNotificationParameter = 1;
    initiator.forceDfu = YES;
    initiator.logger = self;
    initiator.delegate = self;
    initiator.progressDelegate = self;
    initiator.enableUnsafeExperimentalButtonlessServiceInSecureDfu = YES;
    initiator.alternativeAdvertisingNameEnabled = false;
    _controller = [initiator startWithTarget:_bluetoothTemp];
}

//更新进度状态  升级开始..升级中断..升级完成等状态
- (void)dfuStateDidChangeTo:(enum DFUState)state{
    
    NSLog(@"DFUState state%ld",state);
    //升级完成
    if (state==DFUStateCompleted) {
        NSLog(@"升级完成");
        self.DFUReturn(@"{\"content\":\"升级成功\"}");
    }
}

//更新进度
- (void)dfuProgressDidChangeFor:(NSInteger)part outOf:(NSInteger)totalParts to:(NSInteger)progress currentSpeedBytesPerSecond:(double)currentSpeedBytesPerSecond avgSpeedBytesPerSecond:(double)avgSpeedBytesPerSecond{
    self.DFUReturn([NSString stringWithFormat:@"{\"content\":\"%f\"}",(float)progress/totalParts/100]);
}

//升级error信息
- (void)dfuError:(enum DFUError)error didOccurWithMessage:(NSString * _Nonnull)message{

    NSLog(@"错误 %ld: %@", (long) error, message);
    self.DFUReturn([NSString stringWithFormat:@"{\"content\":\"升级失败\",\"error\":\"%@\"}",message]);
}

-(void)logWith:(enum LogLevel)level message:(NSString *)message
{
    NSLog(@"%logWith ld: %@", (long) level, message);
}


- (void)stopScan{
    [self.centralManager stopScan];
}

- (void)disconnect{
     [self.centralManager cancelPeripheralConnection:self.bluetoothTemp];
}

@end
